
#include <BPainter>
#include "member_BVBoxLayout.h"

using namespace BWE;

member_BVBoxLayout::member_BVBoxLayout(BVBoxLayout* layout)
{
	boss = layout;
}
member_BVBoxLayout::~member_BVBoxLayout()
{

}

int member_BVBoxLayout::distributeHeight(int remainHeight)
{
	int visualCount = 0;
	for (int i = 0; i < items.size(); i++)
	{
		LayoutItem& item = items[i];
		if (item.prepare(remainHeight))
			visualCount++;
	}
	if (visualCount == 0)
		return remainHeight;

	while (remainHeight != 0)
	{
		float totalStretch = 0;
		for (int i = 0; i < items.size(); i++)
		{
			if (items[i].finishHeight)
				continue;
			totalStretch += items[i].sizeStretch().heightStretch();
		}
		if (totalStretch < 0.00001)
			break;

		int used = 0;
		for (int i = 0; i < items.size(); i++)
		{
			LayoutItem& item = items[i];

			if (item.finishHeight)
				continue;
			int height = item.sizeStretch().heightStretch() / totalStretch * remainHeight;
			if (height == 0)
				continue;
			int maxHeight = item.maxSize().height();
			int minHeight = item.minSize().height();
			if (height + item.realSize.height() > maxHeight)
			{
				used += maxHeight - item.realSize.height();
				item.realSize.setHeight(maxHeight);
				item.finishHeight = true;
				continue;
			}
			if (height + item.realSize.height() < minHeight)
			{
				used += minHeight - item.realSize.height();
				item.realSize.setHeight(minHeight);
				item.finishHeight = true;
				continue;
			}
			used += height;
			item.realSize += BSize(0, height);
		}
		if (used == 0)
			break;
		remainHeight -= used;
	}
	while (remainHeight > 0)
	{
		for (int i = 0; i < items.size(); i++)
		{
			if (items[i].ignored())
				continue;
			items[i].realSize.height() += 1;
			remainHeight--;
			if (remainHeight < 1)
				break;
		}
	}
	return remainHeight;
}
